package cn.edu.hnu.gpg.api;

import cn.edu.hnu.gpg.api.error.*;
import cn.edu.hnu.gpg.dto.Account;
import cn.edu.hnu.gpg.dto.AnswerToQuestion;
import cn.edu.hnu.gpg.entity.Answer;
import cn.edu.hnu.gpg.entity.Student;
import cn.edu.hnu.gpg.entity.Teacher;
import cn.edu.hnu.gpg.entity.User;
import cn.edu.hnu.gpg.entity.enums.UserType;
import cn.edu.hnu.gpg.service.*;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/api/teacher")
public class TeacherApiController {

    public static class SendMessageRequest {
        private List<Integer> receivers;
        private String content;

        public void setContent(String content) {
            this.content = content;
        }

        public String getContent() {
            return content;
        }

        public void setReceivers(List<Integer> receivers) {
            this.receivers = receivers;
        }

        public List<Integer> getReceivers() {
            return receivers;
        }
    }

    static private final Logger logger = LogManager.getLogger(TeacherApiController.class);
    private final QuestionService questionService;
    private final StudentService studentService;
    private final AnswerService answerService;
    private final TeacherService teacherService;
    private final SupervisionService supervisionService;
    private final MessageService messageService;
    @Autowired
    public TeacherApiController(TeacherService teacherService, StudentService studentService, QuestionService questionService, AnswerService answerService, SupervisionService supervisionService, MessageService messageService){
        this.teacherService = teacherService;
        this.studentService = studentService;
        this.questionService = questionService;
        this.answerService = answerService;
        this.supervisionService = supervisionService;
        this.messageService = messageService;
    }

    @RequestMapping(value = "search_account", method = RequestMethod.GET)
    @ResponseBody
    public List<Account> searchAccounts(HttpServletRequest request) throws InvalidArgumentException {
        User user =(User)request.getSession(true).getAttribute("user");
        Teacher teacher = teacherService.findTeacherByUserId(user.getUserId());
        List<Integer> studentList = supervisionService.findStudentIdByTeacher(teacher);
        if (studentList == null)
            return null;
        List<Account> accountList = new ArrayList<>();
        for (Integer id : studentList){
            accountList.add(new Account(studentService.findStudentByStudentId(id)));
        }
        return accountList;
    }

    @RequestMapping(value = "/{questionId}", method = RequestMethod.GET)
    @ResponseBody
    public Answer requestAnswer(HttpServletRequest request, @PathVariable Integer questionId) throws UnknownException {
        try {
            List<Answer> answers = answerService.getAllAnswerToQuestion(questionId);
            if (answers == null){
                Answer answer = new Answer();
                answer.setQuestionId(questionId);
                answer.setAnswerTime(new Date());
                answer.setContent("尚未有有效回答，请静待做出回答");
                return answer;
            }
            logger.info("answer:"+answers.get(0).getContent());
            return answers.get(0);
        } catch (Exception e) {
            logger.debug(e.getCause());
            throw new UnknownException();
        }
    }

    @RequestMapping(value = "/updateAnswer", method = RequestMethod.POST)
    @ResponseBody
    public int updateAnswer(HttpServletRequest request, @RequestBody AnswerToQuestion answerToQuestion) throws UnknownException {
        try {
            int question_id = answerToQuestion.getQuestion_id();
            String answer = answerToQuestion.getAnswer();
            logger.info("question_id:"+question_id+" answer:"+answer);
            User user = (User) request.getSession(true).getAttribute("user");
            List <Answer> answers = answerService.getAllAnswerToQuestion(question_id);
            if (answers != null)
                return answerService.updateByQuestionId(question_id,answer);
            return answerService.createAnswer(user.getUserId(),question_id,answer);
        } catch (Exception e) {
            logger.debug(e.getCause());
            throw new UnknownException();
        }
    }

    @RequestMapping(value = "/send_message", method = RequestMethod.POST)
    @ResponseBody
    public void sendMessage(HttpServletRequest request, @RequestBody SendMessageRequest requestBody) throws PermissionDeniedException, InvalidArgumentException {
        User user = ((User) request.getSession().getAttribute("user"));

        if (user.getUserType() != UserType.T)
            throw new PermissionDeniedException("User must be teacher type");

        if (requestBody.receivers == null) {
            throw new InvalidArgumentException(new ApiError(ApiError.ErrorType.ERR_MISSING_PARAMETER,
                    "Required List parameter 'receivers' is not present"));
        }
        if (requestBody.receivers.isEmpty()) {
            throw new InvalidArgumentException(new ApiError(ApiError.ErrorType.ERR_INVALID_METHOD_ARGUMENT,
                    "Required argument 'receivers' is an empty list"));
        }
        if (requestBody.content == null) {
            throw new InvalidArgumentException(new ApiError(ApiError.ErrorType.ERR_MISSING_PARAMETER,
                    "Required List parameter 'content' is not present"));
        }
        if (requestBody.content.isEmpty()) {
            throw new InvalidArgumentException(new ApiError(ApiError.ErrorType.ERR_INVALID_METHOD_ARGUMENT,
                    "Required argument 'content' is an empty string"));
        }

//        Teacher teacher = teacherService.findTeacherByUserId(user.getUserId());
        messageService.sendMessage(user.getUserId(), requestBody.receivers, requestBody.content);
    }
}
